package br.com.guiav6.sisguia.utils;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import br.com.guiav6.sisguia.bean.AnuncioBean;
import br.com.guiav6.sisguia.service.TipoServicoService;

@Component("servicoEspecialidadeConverter")
@Scope(value = "session")
public class ServicoEspecialidadeConverter implements Converter {
	
	@Autowired
	TipoServicoService tipoServicoService;

	@Override
	public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
		if(value != null){
			AnuncioBean bean = new AnuncioBean();
			int index = value.indexOf("#{-}");
			String idServico = index > 0 ? value.substring(0, index - 1) : value;
			String idEspecialidade = index > 0 ? value.substring(index + 5, value.length()) : null;
			if (!NumberUtils.isNumber(idServico))
				return bean;
			bean.setIdServico(Long.valueOf(idServico));
			if(idEspecialidade != null)
				bean.setIdEspecialidade(Long.valueOf(idEspecialidade));
			return bean;			
		}else
			return null;
	}

	@Override
	public String getAsString(FacesContext fc, UIComponent uic, Object value) {
		String ids = "";
		if(value != null){
			if (((AnuncioBean) value).getIdServico() == null){
				return "";
			}
			String idServico = ((AnuncioBean) value).getIdServico().toString();
			if(((AnuncioBean) value).getIdEspecialidade() != null)
				ids = idServico + " #{-} " + ((AnuncioBean) value).getIdEspecialidade();
			return ids.equals("") ? idServico : ids;
		}
		return "";
	}

}